package scheduler;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;

public class Scheduler implements Runnable{

	private int _port; 
	private LinkedBlockingQueue<Task> _submitQueue;
	private Socket _connectionSocket;
	private LinkedBlockingQueue<Task> tasksDone;


	public Scheduler(int port, LinkedBlockingQueue<Task> submitQueue, LinkedBlockingQueue<Task> done) {
		_port = port; 
		_submitQueue = submitQueue;
		tasksDone = done; 
	}

	private void parseMessage(String msg) {
		String[] message = msg.split(" ");
		if(message[0].equalsIgnoreCase("0")){
			String[] task = message[1].split("/");
			_submitQueue.add(new Task(task[0], task[1])); 
		}else {
			for (int i=1; i< message.length; i++){
				String[] task = message[i].split("/");
				_submitQueue.add(new Task(task[0], task[1]));
			}
		}
	}


	@Override
	public void run() {
		ServerSocket welcomeSocket;
		try {
			while(true){
				welcomeSocket = new ServerSocket(_port);
				_connectionSocket = welcomeSocket.accept();
				while(_connectionSocket.isConnected())
				{
					readFromClient(); 
					writeToClient();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void readFromClient() throws IOException {
		String msg;
		BufferedReader inFromClient = new BufferedReader(new InputStreamReader(_connectionSocket.getInputStream()));
		msg = inFromClient.readLine();
		parseMessage(msg);
	}

	private void writeToClient() throws IOException {
		if (!tasksDone.isEmpty()){
			DataOutputStream outToClient = new DataOutputStream(_connectionSocket.getOutputStream());
			String toClient = String.valueOf(tasksDone.size());
			for(int i=0; i<tasksDone.size(); i++){
				Task task = tasksDone.poll(); 
				toClient += " " + task.getId().toString() + "/" + String.valueOf(task.getResult());			
			}
			outToClient.writeChars(toClient);
		}
	}	
}
